/**
 * Copyright &copy; 2012-2016 <a href="https://www.kaaction.com">KAA</a> All rights reserved All rights reserved.
 */
package com.kaaction.modules.crab.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.kaaction.common.beanvalidator.BeanValidators;
import com.kaaction.common.config.Global;
import com.kaaction.common.persistence.Page;
import com.kaaction.common.web.BaseController;
import com.kaaction.common.utils.DateUtils;
import com.kaaction.common.utils.StringUtils;
import com.kaaction.common.utils.excel.ExportExcel;
import com.kaaction.common.utils.excel.ImportExcel;
import com.kaaction.modules.crab.entity.CouponDetail;
import com.kaaction.modules.crab.service.CouponDetailService;
import com.kaaction.modules.sys.entity.User;
import com.kaaction.modules.sys.utils.UserUtils;

/**
 * 兑换券查看Controller
 * @author huanghaiming
 * @version 2017-07-19
 */
@Controller
@RequestMapping(value = "${adminPath}/crab/couponDetail")
public class CouponDetailController extends BaseController {

	@Autowired
	private CouponDetailService couponDetailService;
	
	@ModelAttribute
	public CouponDetail get(@RequestParam(required=false) String id) {
		CouponDetail entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = couponDetailService.get(id);
		}
		if (entity == null){
			entity = new CouponDetail();
		}
		return entity;
	}
	
	@RequiresPermissions("crab:couponDetail:view")
	@RequestMapping(value = {"list", ""})
	public String list(CouponDetail couponDetail, HttpServletRequest request, HttpServletResponse response, Model model) {
		couponDetailService.udateCouponName(couponDetail);
		Page<CouponDetail> page = couponDetailService.findPage(new Page<CouponDetail>(request, response), couponDetail); 
		model.addAttribute("page", page);
		return "modules/crab/couponDetailList";
	}

	@RequiresPermissions("crab:couponDetail:form")
	@RequestMapping(value = "form")
	public String form(CouponDetail couponDetail, Model model) {
		model.addAttribute("couponDetail", couponDetail);
		return "modules/crab/couponDetailForm";
	}

	@RequiresPermissions("crab:couponDetail:save")
	@RequestMapping(value = "save")
	public String save(CouponDetail couponDetail, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, couponDetail)){
			return form(couponDetail, model);
		}
		couponDetailService.save(couponDetail);
		addMessage(redirectAttributes, "保存兑换券查看成功");
		return "redirect:"+Global.getAdminPath()+"/crab/couponDetail/?repage&couponId="+couponDetail.getCouponId()+"&couponName="+couponDetail.getCouponName();
	}
	
	@RequiresPermissions("crab:couponDetail:delete")
	@RequestMapping(value = "delete")
	public String delete(CouponDetail couponDetail, RedirectAttributes redirectAttributes) {
		couponDetailService.delete(couponDetail);
		addMessage(redirectAttributes, "删除兑换券查看成功");
		return "redirect:"+Global.getAdminPath()+"/crab/couponDetail/?repage&couponId="+couponDetail.getCouponId()+"&couponName="+couponDetail.getCouponName();
	}
	
	
	/**
	 * 导出兑换券数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("crab:couponDetail:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(CouponDetail couponDetail, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "兑换券数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            List<CouponDetail> list = couponDetailService.findCouponDetail(couponDetail);
    		new ExportExcel("兑换券数据", CouponDetail.class).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出兑换券数据失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/crab/couponDetail/?repage";
    }
	
	/**
	 * 下载导入兑换券数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("crab:couponDetail:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "兑换券数据导入模板.xlsx";
    		List<CouponDetail> list = Lists.newArrayList();
    		new ExportExcel("兑换券数据", CouponDetail.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/crab/couponDetail/list?repage";
    }
	
	
	/**
	 * 导入兑换券数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("crab:couponDetail:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file,CouponDetail entity,RedirectAttributes redirectAttributes) {
		String couponId = entity.getCouponId();
		try {
			int successNum = 0;
			int failureNum = 0;
			User user = UserUtils.getUser();
			String name = user.getName();
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<CouponDetail> list = ei.getDataList(CouponDetail.class);
			
			int a =0;
			
			List<String> strList = Lists.newArrayList();
			
			for (CouponDetail couponDetail : list){
				String cardNum = couponDetail.getCardNum();
				if(cardNum!=null&&!"".equals(cardNum)){
					if(!strList.contains(cardNum)){
						strList.add(cardNum);
					}else{
						a++;
						break;
					}
				}
				
			}
			
			if(a==0){
				int scnt = couponDetailService.selCnt(strList);
				
				if(scnt>0){
					addMessage(redirectAttributes, "存在相同的兑换券号,导入失败");
				}else{
					boolean b = true; 
					for (CouponDetail couponDetail : list){
						try{
							BeanValidators.validateWithException(validator, couponDetail);
							couponDetail.setCouponId(couponId);
							String activatedState = couponDetail.getActivatedState();
							String aState = "";
							if("未激活".equals(activatedState)){
								aState="0";
							}else if("已激活".equals(activatedState)){
								aState="1";
							}else if("已作废".equals(activatedState)){
								aState="2";
							}else{
								failureMsg.append("<br/>激活状态为：未激活,已激活或已作废");
								failureNum++;
								b = false;
							}
							if(b){
								int cnt  = couponDetailService.getEqual(couponDetail.getCardNum());
								couponDetail.setActivatedState(aState);
								couponDetail.setUseState("0");
								if(cnt==0){
									couponDetailService.save(couponDetail);
								}else{
									couponDetailService.updateCoupon(couponDetail);
								}
								successNum++;
							}
							
						}catch(ConstraintViolationException ex){
							failureMsg.append("<br/>登录名 "+name+" 导入失败：");
							List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
							for (String message : messageList){
								failureMsg.append(message+"; ");
								failureNum++;
							}
						}catch (Exception ex) {
							failureMsg.append("<br/>登录名 "+name+" 导入失败："+ex.getMessage());
						}
					}
					if (failureNum>0){
						failureMsg.insert(0, "，失败 "+failureNum+" 条兑换券信息，导入信息如下：");
					}
					addMessage(redirectAttributes, "已成功导入 "+successNum+" 条兑换券信息"+failureMsg);
				}
			}else{
				addMessage(redirectAttributes, "导入失败:excel文档存在相同卡号");
			}
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入兑换券信息失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/crab/couponDetail/list?repage&couponId="+entity.getCouponId()+"&couponName="+entity.getCouponName();
    }
	
	/**
	 * 批量备注
	 * @param couponDetail
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("crab:couponDetail:batchRemarks")
	@RequestMapping(value = "batchRemarks", method=RequestMethod.POST)
	public String batchRemarks(CouponDetail couponDetail, RedirectAttributes redirectAttributes) {
		 String numStart =  couponDetail.getNumStart();
		 String numEnd =  couponDetail.getNumEnd();
		 String remarks =  couponDetail.getRemarks();
		 if("".equals(numStart)||"".equals(numEnd)){
			 addMessage(redirectAttributes, "兑换券不能为空");
		 }else if(numStart.length()<=4||numEnd.length()<=4){
			 addMessage(redirectAttributes, "兑换券输入不正确");
		 }else{
			 if("".equals(remarks)){
				 addMessage(redirectAttributes, "备注不能为空");
			 }else{
				
				String numS = numStart.substring(0,numStart.length()-4);
				String numE = numEnd.substring(0,numEnd.length()-4);
				if(numS.equals(numE)){
					couponDetailService.updateBatchRemarks(couponDetail);
				}else{
					 addMessage(redirectAttributes, "兑换券号前后不一致");
				}
			 }
		 }
		 return "redirect:"+adminPath+"/crab/couponDetail/list?repage&couponId="+couponDetail.getCouponId()+"&couponName="+couponDetail.getCouponName();
	}
	
	/**
	 *  批量激活/非激活
	 * @param couponDetail
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("crab:couponDetail:batchActivate")
	@RequestMapping(value = "batchActivate", method=RequestMethod.POST)
	public String batchActivate(CouponDetail couponDetail, RedirectAttributes redirectAttributes) {
		 String numStart =  couponDetail.getNumStart();
		 String numEnd =  couponDetail.getNumEnd();
		 if("".equals(numStart)||"".equals(numEnd)){
			 addMessage(redirectAttributes, "兑换券不能为空");
		 }else if(numStart.length()<=4||numEnd.length()<=4){
			 addMessage(redirectAttributes, "兑换券输入不正确");
		 }else{
			 String numS = numStart.substring(0,numStart.length()-4);
				String numE = numEnd.substring(0,numEnd.length()-4);
				if(numS.equals(numE)){
					 couponDetailService.updateBatchActivate(couponDetail);
				}else{
					 addMessage(redirectAttributes, "兑换券号前后不一致");
				}
		 }
		 return "redirect:"+adminPath+"/crab/couponDetail/list?repage&couponId="+couponDetail.getCouponId()+"&couponName="+couponDetail.getCouponName();
	}

}